package com.example.wemedia.controller;

import com.example.wemedia.service.WmMaterialService;
import com.usian.common.alibaba.GreeTextScanUtil;
import com.usian.common.alibaba.GreenImageScanUtil;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FileUploadController {
    @Autowired
    FastDFSClient fastDFSClient;
    @Value("${fastdfs.url}")
    private String prefixUrl;
    @Autowired
    private WmMaterialService wmMaterialService;
    @Autowired
    private GreenImageScanUtil greenImageScanUtil;
    @PostMapping("/wemedia/v1/upload_file")
    public ResponseResult upload(MultipartFile file,String type) throws Exception {
        List<byte[]> imageList = new ArrayList<byte[]>();
        byte[] bytes = file.getBytes();
        imageList.add(bytes);
        String s = greenImageScanUtil.imageScan(imageList);
        if (s==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (s.equals("pass")){
            String imgUrl = fastDFSClient.uploadFile(file);
            Integer integer = wmMaterialService.saveMasterail(type, imgUrl);
            if (integer==1){
                return ResponseResult.okResult(prefixUrl+imgUrl);
            }
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (s.equals("block")){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_FAIL);
        }
        else{
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

    }
}
